package com.lzq.chatroom_project.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lzq.chatroom_project.common.pojo.Result;
import com.lzq.chatroom_project.common.pojo.ResultCode;
import com.lzq.chatroom_project.model.AddFriendRequest;
import com.lzq.chatroom_project.model.Friend;
import com.lzq.chatroom_project.model.OnlineUserManager;
import com.lzq.chatroom_project.model.User;
import com.lzq.chatroom_project.service.impl.FriendServiceImpl;
import com.lzq.chatroom_project.service.impl.UserServiceImpl;
import com.lzq.chatroom_project.common.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/friend")
public class FriendController {
    @Autowired
    private FriendServiceImpl friendService;
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private OnlineUserManager onlineUserManager;
    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 获取好友列表
     * @param request
     * @return Result(friendList)
     */
    @GetMapping("/getFriendList")
    public Result getFriendList(HttpServletRequest request) {
        log.info("开始执行getFriendList方法");
        String jwt = request.getHeader("user_token");
        Integer userId = (Integer) JwtUtil.getUserIdFromToken(jwt).getData();
        if (userId == null || userId <= 0) {
            log.error("查询到的用户id:{}",userId);
            return Result.failed(ResultCode.FAILED);
        }
        //根据userId获取好友列表
        List<Friend> friendList = friendService.getFriendListById(userId);
        if (friendList == null) {
            log.info("查询到的用户列表为空");
            return Result.success(new ArrayList<>());
        }
        return Result.success(friendList);
    }

    /**
     * (模糊)根据用户名寻找好友
     * @param friendName
     * @param session
     * @return Result(friendList)
     */
    @GetMapping("/findFriend")
    public Result findFriend(String friendName, HttpSession session) {
        log.info("开始执行findFriend方法,接收参数:friendName:{}",friendName);
        User user = (User)session.getAttribute("user");
        if (user == null || user.getUserId() <= 0) {
            log.error("查询到的用户user:{}",user);
            return Result.failed(ResultCode.FAILED);
        }
        //根据userId和friendName模糊寻找好友
        List<Friend> friendList = friendService.findFriend(user.getUserId(),friendName);
        if (friendList == null) {
            log.info("查询到的好友为空");
            return Result.success(new ArrayList<Friend>());
        }
        return Result.success(friendList);
    }

    /**
     * 添加好友
     * @param friendId
     * @param reason
     * @param session
     * @return Result("")
     * @throws IOException
     */
    @GetMapping("/addFriend")
    public Result addFriend(int friendId, String reason, HttpSession session) throws IOException {
        log.info("开始执行addFriend方法, 接收参数:friendId:{}, reason:{}", friendId, reason);
        User user = (User)session.getAttribute("user");
        if (user == null || user.getUserId() <= 0) {
            log.error("查询到的用户user:{}",user);
            return Result.failed(ResultCode.FAILED);
        }
        //增加添加好友请求
        friendService.addFriendRequest(user.getUserId(), friendId, reason);
        //根据friendId获取对应的webSocketSession
        WebSocketSession webSocketSession = onlineUserManager.getSession(friendId);
        if (webSocketSession != null) {
            AddFriendRequest addFriendRequest = new AddFriendRequest();
            addFriendRequest.setType("addFriendRequest");
            addFriendRequest.setFromUserId(user.getUserId());
            addFriendRequest.setFromUserName(user.getUsername());
            addFriendRequest.setReason(reason);
            webSocketSession.sendMessage(new TextMessage(objectMapper.writeValueAsString(addFriendRequest)));
        }
        return Result.success("");
    }

    /**
     * 获取好友请求
     * @param session
     * @return Result(addFriendRequestList)
     * @throws IOException
     */
    @GetMapping("/getFriendRequest")
    public Result getFriendRequest(HttpSession session) throws IOException {
        log.info("开始执行getFriendRequest方法");
        User user = (User)session.getAttribute("user");
        if (user == null || user.getUserId() <= 0) {
            log.error("查询到的用户user:{}",user);
            return Result.failed(ResultCode.FAILED);
        }
        //根据userId查询对他的添加好友的请求
        List<AddFriendRequest> addFriendRequestList = new ArrayList<>();
        addFriendRequestList = friendService.getFriendRequest(user.getUserId());
        return Result.success(addFriendRequestList);
    }

    /**
     * 接受添加好友请求
     * @param friendId
     * @param session
     * @return Result("")
     * @throws IOException
     */
    @GetMapping("/acceptFriend")
    @Transactional
    public Result acceptFriend(int friendId,HttpSession session) throws IOException{
        log.info("开始执行acceptFriend方法,接收参数:friendId:{}",friendId);
        User user = (User)session.getAttribute("user");
        if (user == null || user.getUserId() <= 0) {
            log.error("查询到的用户user:{}",user);
            return Result.failed(ResultCode.FAILED);
        }
        //删除添加好友的请求
        friendService.deleteFriendRequest(friendId,user.getUserId());
        String friendName = userService.getUserById(friendId).getUsername();
        //添加好友
        friendService.addFriend(friendId,user.getUserId(),friendName,user.getUsername());
        //根据friendId获取对应的webSocketSession
        WebSocketSession webSocketSession = onlineUserManager.getSession(friendId);
        if (webSocketSession != null) {
            AddFriendRequest addFriendRequest = new AddFriendRequest();
            addFriendRequest.setType("acceptFriend");
            addFriendRequest.setFromUserId(user.getUserId());
            addFriendRequest.setFromUserName(user.getUsername());
            addFriendRequest.setReason("");
            webSocketSession.sendMessage(new TextMessage(objectMapper.writeValueAsString(addFriendRequest)));
        }
        return Result.success("");
    }

    /**
     * 拒绝添加好友请求
     * @param friendId
     * @param session
     * @return Result("")
     */
    @GetMapping("/rejectFriend")
    @Transactional
    public Result rejectFriend(int friendId,HttpSession session) {
        log.info("开始执行rejectFriend方法,接收参数:friendId:{}",friendId);
        User user = (User)session.getAttribute("user");
        if (user == null || user.getUserId() <= 0) {
            log.error("查询到的用户user:{}",user);
            return Result.failed(ResultCode.FAILED);
        }
        //删除添加好友的请求
        friendService.deleteFriendRequest(friendId,user.getUserId());
        return Result.success("");
    }

    /**
     * 修改好友昵称
     * @param friendNickname
     * @param session
     * @return Result("")
     */
    @PostMapping("/updateFriendNickname")
    public Result updateFriendNickname(int friendId,String friendNickname,HttpSession session) {
        log.info("开始执行updateFriendNickname方法,接收参数:friendNickname:{}",friendNickname);
        User user = (User)session.getAttribute("user");
        if (user == null || user.getUserId() <= 0) {
            log.error("查询到的用户user:{}",user);
            return Result.failed(ResultCode.FAILED);
        }
        //修改好友昵称
        friendService.updateFriendNickname(friendId,user.getUserId(),friendNickname);
        return Result.success("");
    }
}
